﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：DefaultApiValidateImage.cs
// 功能描述：TongTongMall.MallWeb.Core
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TEC.Web.Component.ValidateCode;
using TongTongMall.Dependecy;
using TongTongMall.Events;
using TongTongMall.MallWeb.Core.Events.EventDatas;
using TongTongMall.Redis.Cache;
using TongTongMall.Runtime.Session;

namespace TongTongMall.MallWeb.Application.Configuration.Instance
{
    /// <summary>
    /// 默认验证码图片对象
    /// </summary>
    public class DefaultApiValidateImage : ValidateImageBase, ITransientDependency
    {
        private string type { get; set; }

        /// <summary>
        /// 事件总线
        /// </summary>
        public IEventBus EventBus { get; set; }

        /// <summary>
        /// 当前访问信息
        /// </summary>
        public ITongTongMallSession Session{ get; set; }

        private readonly IRedisCache _redisCache;

        /// <summary>
        /// 构函数 默认用途类型：“login”
        /// </summary>
        public DefaultApiValidateImage(IRedisCache redisCache) : this("login")
        {
            EventBus = NullEventBus.Instance;
            _redisCache = redisCache;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="type">用途类型</param>
        public DefaultApiValidateImage(string type)
        {
            this.type = type;
        }

        protected override string CreateCheckCode()
        {
            return TEC.Public.Common.UtilityHelper.GetRandomString(4, false, true, true, false);
        }
        protected override object GetTempSavedCode(object id)
        {
            return _redisCache.GetOrDefault(Session.TenantName + ":" + id.ToString() + ":imgvcode_" + type);
        }

        protected override void RemoveTempSaveCode(object id)
        {
            EventBus.Trigger(typeof(RedisRemoveEventData), this, new RedisRemoveEventData { Keys = Session.TenantName + ":" + id.ToString() + ":imgvcode_" + type});
        }

        protected override void SaveTempCode(string code, object id)
        {
            EventBus.Trigger(typeof(RedisParameterEventData), this, new RedisParameterEventData { Keys = Session.TenantName + ":" + id.ToString() + ":imgvcode_" + type, Data = code, Expire = new TimeSpan(0, 5, 0) });
        }
    }
}
